/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Facades;

import Entities.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author roycalderon
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {

    @PersistenceContext(unitName = "MaRoY-LibraryPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }

    //Roy: Used4Login->
    public User FindUserAndPass(String user, String pass) {
        User aux;
        if (!user.isEmpty() & !pass.isEmpty()) {
            try {
                Query query = em.createQuery("SELECT v FROM User v WHERE v.userName = :userName and v.passWord = :passWord");
                query.setParameter("userName", user);
                query.setParameter("passWord", pass);
                aux = (User) query.getSingleResult();
                if (aux != null) {
                    return aux;
                } else {
                    return null;
                }
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

    public User FindbyUser(String usuario) {
        Query query = em.createNamedQuery("User.findByUserName");
    query.setParameter("userName", usuario);
        User aux;
        try {
            aux = (User) query.getSingleResult();
            if (aux != null) {
                return aux;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public User FindbyId(int userId) {
        Query query = em.createNamedQuery("User.findById");
        query.setParameter("id", userId);
        User aux;
        try {
            aux = (User) query.getSingleResult();
            if (aux != null) {
                return aux;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
}
